package com.android.lovely.data

import android.content.res.Resources
import android.util.Base64
import android.util.Log
import androidx.core.os.ConfigurationCompat
import com.kotlin.extensions.appContext
import com.kotlin.extensions.coroutine.CoroutineExt.doOnIO
import com.kotlin.extensions.json.JsonExt.fromJsonByType
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.util.Locale

/**
 *
 * @author why
 * @date 2025/3/6 18:55
 */
@JsonClass(generateAdapter = true)
data class Language(
    @Json(name = "code") val code: String = "",
    @Json(name = "name") val name: String = ""
)

/**
 * 混淆后的JSON数据模型
 * x 代表 code（语言代码）Base64编码
 * y 代表 name（语言名称）Base64编码
 * z 是干扰数据
 */
@JsonClass(generateAdapter = true)
internal data class ObfuscatedLanguage(
    @Json(name = "x") val x: String = "",
    @Json(name = "y") val y: String = "",
    @Json(name = "z") val z: String = ""
)

val deviceLanguage: String
    get() = ((ConfigurationCompat.getLocales(Resources.getSystem().configuration)
        .get(0)?.language ?: Locale.getDefault().language ?: "en").split("-").firstOrNull()
        ?: "en").lowercase()

/**
 * 解码Base64字符串
 * 
 * @param encoded Base64编码的字符串
 * @return 解码后的字符串
 */
private fun decodeBase64String(encoded: String): String {
    return try {
        String(Base64.decode(encoded, Base64.DEFAULT))
    } catch (e: Exception) {
        Log.e("Language", "解码失败: $encoded", e)
        ""
    }
}

/**
 * 获取语言列表
 * 
 * @return 解码并排序后的语言列表
 */
suspend fun getLanguages(): List<Language> {
    return doOnIO {
        val jsonText = appContext.assets.open("language.json").reader().readText()
        Log.d("Language", "读取混淆的JSON数据")
        
        // 解析为混淆后的数据结构
        val obfuscatedList = jsonText.fromJsonByType<List<ObfuscatedLanguage>>().orEmpty()
        
        // 转换为正常的Language对象列表
        obfuscatedList.map { obfuscated ->
            Language(
                code = decodeBase64String(obfuscated.x),
                name = decodeBase64String(obfuscated.y)
            )
        }.sortedBy { it.name }
    }
}